package com.niiwoo.civet.user.service.local;

import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.user.dao.entity.*;
import com.niiwoo.civet.user.dao.mapper.DataStatusMapperExt;
import com.niiwoo.civet.user.dao.mapper.UserLinkmanInfoMapperExt;
import com.niiwoo.civet.user.dao.mapper.UserPersonalInfoMapper;
import com.niiwoo.civet.user.dao.mapper.UserProfessionInfoMapper;
import com.niiwoo.civet.user.dto.request.LoanDataAuthenticationRequestDTO;
import com.niiwoo.civet.user.dto.response.LoanDataAuthenticationResponseDTO;
import com.niiwoo.civet.user.dto.response.UserCreditDataStatusResponseDTO;
import com.niiwoo.civet.user.enums.UserDataStatusEnum;
import com.niiwoo.civet.user.enums.UserDataTypeEnum;
import com.niiwoo.civet.user.enums.UserImgTypeEnum;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 用户状态本地服务
 */
@Slf4j
@Service
public class UserStatusService {

    @Autowired
    DataStatusMapperExt ucDataStatusMapperExt;
    @Autowired
    UserImageFileService imageFileService;
    @Autowired
    SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    UserIdentityService userIdentityService;
    @Autowired
    UserPersonalInfoMapper userPersonalInfoMapper;
    @Autowired
    UserProfessionInfoMapper userProfessionInfoMapper;
    @Autowired
    UserLinkmanInfoMapperExt userLinkmanInfoMapper;


    /**
     * 获取用户状态
     *
     * @param userId   用户id
     * @param dataType 数据类型
     */
    public DataStatus getByUserIdAndType(String userId, UserDataTypeEnum dataType) {
        return ucDataStatusMapperExt.selectByUserIdAndType(userId, dataType.getValue());
    }

    /**
     * 获取用户状态列表
     *
     * @param userId
     * @return
     */
    public List<DataStatus> getDataStatusByUserId(String userId) {
        return ucDataStatusMapperExt.getDataStatusByUserId(userId);
    }

    /**
     * 根据用户和类型修改状态
     *
     * @param dataStatus
     * @return
     */
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public int updateDataStatusByUserIdAndType(DataStatus dataStatus) {
        return ucDataStatusMapperExt.updateByUserIdAndType(dataStatus);
    }

    /**
     * 根据用户和类型：保存用户的状态变更
     * 不存在插入，存在更新
     *
     * @param dataStatus
     * @return int
     * @author zzl
     * @date 2017/11/23 15:58
     */
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public int saveDataStatusByUserIdAndType(DataStatus dataStatus) {

        DataStatus selectDataStatus = ucDataStatusMapperExt.selectByUserIdAndType(dataStatus.getUserId(), dataStatus.getDataType());
        if (selectDataStatus == null) {
            dataStatus.setId(snowflakeIdWorker.nextId());
            dataStatus.setCreateTime(new Date());
            dataStatus.setAuthTime(new Date());
            dataStatus.setUpdateTime(new Date());
            return ucDataStatusMapperExt.insertSelective(dataStatus);
        }
        dataStatus.setAuthTime(new Date());
        dataStatus.setUpdateTime(new Date());
        int result = ucDataStatusMapperExt.updateByUserIdAndType(dataStatus);
        log.info("UserStatusService.saveDataStatusByUserIdAndType dataStatus={}", JSON.toJSONString(dataStatus));
        return result;
    }

    /**
     * 根据类型和AuthTime获取数据
     */
    public List<DataStatus> getByTypeAndTime(Byte dataType, Date startDate, Date endDate, Byte dataStatus) {
        return ucDataStatusMapperExt.getByTypeAndTime(dataType, startDate, endDate, dataStatus);
    }

    /**
     * 区分认证结果返回
     */
    @Transactional(rollbackFor = Exception.class)
    public LoanDataAuthenticationResponseDTO loanDataAuthentication(LoanDataAuthenticationRequestDTO requestDTO) {
        log.info("UserDataDubbServiceImpl.loanDataAuthentication request={}", JSON.toJSON(requestDTO));

        UserCreditDataStatusResponseDTO userStatus = this.selectUserDataStatus(requestDTO);

        LoanDataAuthenticationResponseDTO responseDTO = new LoanDataAuthenticationResponseDTO();
        responseDTO.setIdentityInfoStatus(Byte.valueOf("0"));
        responseDTO.setOperatorAuthorize(userStatus.getPhoneOperatorStatus());
        responseDTO.setSocialSecurityOperatorAuthorize(userStatus.getSocialSecurityStatus());
        responseDTO.setCreditCardAuthorize(userStatus.getCreditCardAuthorize());
        responseDTO.setEducationAuthorize(userStatus.getEducationAuthorize());
        responseDTO.setJdAuthorize(userStatus.getJdAuthorize());
        responseDTO.setPersonalInfo(userStatus.getPersonalInfo());
        responseDTO.setJdAuthTime(userStatus.getJdAuthTime());
        responseDTO.setEducationTime(userStatus.getEducationTime());
        responseDTO.setCreditCardTime(userStatus.getCreditCardTime());
        responseDTO.setTaobaoAuthorize(userStatus.getTaobaoAuthorize());
        responseDTO.setSocialSecurityTime(userStatus.getSocialSecurityTime());

        // 身份认证：关闭OCR，判断手持照是否上传，如果上传则说明身份信息完成
        if (requestDTO.getOcrScanSwitch() != null && requestDTO.getOcrScanSwitch() == 0
                && userStatus.getHandPhotoStatus() == UserDataStatusEnum.HandPhotoStatus.UPLOADED.getStatus().byteValue()) {
            responseDTO.setIdentityInfoStatus(Byte.valueOf("1"));
        }
        // 已身份证OCR、身份证未过期且离过期日期超过30天、肖像认证成功或信审后台标识为已通过
        if (userStatus.getOcrStatus().equals(UserDataStatusEnum.OCRStatus.YES_OCR.getStatus())
                && userStatus.getTwoElement().equals(UserDataStatusEnum.RealNameAuthStatus.PASS_CERTIFIED.getStatus())
                && (userStatus.getPortraitAuthStatus().equals(UserDataStatusEnum.PortraitAuthStatus.PASS_CERTIFIED.getStatus())
                || userStatus.getPortraitAuthStatus().equals(UserDataStatusEnum.PortraitAuthStatus.NEED_APPROVE.getStatus())
                || userStatus.getPortraitAuthStatus().equals(UserDataStatusEnum.PortraitAuthStatus.REVIEW.getStatus()))
                && userStatus.getIdCardExpiredStatus().equals(UserDataStatusEnum.IdCardExpiredStatus.VALID.getStatus())) {
            responseDTO.setIdentityInfoStatus(Byte.valueOf("1"));
        }
        // 提交成功（OCR已开启情况下）
        if (requestDTO.getOcrScanSwitch() != null && requestDTO.getOcrScanSwitch() == 1
                && userStatus.getOcrStatus().equals(UserDataStatusEnum.OCRStatus.YES_OCR.getStatus())
                && (userStatus.getPortraitAuthStatus().equals(UserDataStatusEnum.PortraitAuthStatus.NEED_APPROVE.getStatus())
                || userStatus.getPortraitAuthStatus().equals(UserDataStatusEnum.PortraitAuthStatus.REVIEW.getStatus()))) {
            responseDTO.setIdentityInfoStatus(Byte.valueOf("4"));
        }
        // 已过期（OCR已开启情况下）
        if (requestDTO.getOcrScanSwitch() != null && requestDTO.getOcrScanSwitch() == 1
                && userStatus.getIdCardExpiredStatus() == UserDataStatusEnum.IdCardExpiredStatus.EXPIRED.getStatus().byteValue()) {
            responseDTO.setIdentityInfoStatus(Byte.valueOf("3"));
        }
        // 快过期（OCR已开启情况下）
        if (requestDTO.getOcrScanSwitch() != null && requestDTO.getOcrScanSwitch() == 1
                && userStatus.getIdCardExpiredStatus() == UserDataStatusEnum.IdCardExpiredStatus.EXPIRING.getStatus().byteValue()) {
            responseDTO.setIdentityInfoStatus(Byte.valueOf("2"));
        }

        // 运营商转换
        if (!userStatus.isPhoneOperatorOverdue() && UserDataStatusEnum.PhoneOperatorStatus.GETFAIL.getStatus().equals(userStatus.getPhoneOperatorStatus())) {
            responseDTO.setOperatorAuthorize(Byte.valueOf("0"));
        }
        if (userStatus.isPhoneOperatorOverdue()
                || UserDataStatusEnum.PhoneOperatorStatus.EXPIRED.getStatus().equals(userStatus.getPhoneOperatorStatus())) {
            responseDTO.setOperatorAuthorize(Byte.valueOf("3"));
        }

        // 社保状态转换
        if (!userStatus.isSocialSecurityOverdue() && UserDataStatusEnum.SocialSecurityStatus.GETFAIL.getStatus().equals(userStatus.getSocialSecurityStatus())
                || UserDataStatusEnum.SocialSecurityStatus.DIFFER.getStatus().equals(userStatus.getSocialSecurityStatus())) {
            responseDTO.setSocialSecurityOperatorAuthorize(Byte.valueOf("0"));
            responseDTO.setSocialSecurityTime(userStatus.getSocialSecurityTime());
        }
        if (userStatus.isSocialSecurityOverdue() || UserDataStatusEnum.SocialSecurityStatus.EXPIRED.getStatus().equals(userStatus.getSocialSecurityStatus())) {
            responseDTO.setSocialSecurityOperatorAuthorize(Byte.valueOf("3"));
            responseDTO.setSocialSecurityTime(userStatus.getSocialSecurityTime());
        }

        // 信用卡状态转换
        if (!userStatus.isCreditCardOverdue() && UserDataStatusEnum.CreditCardStatus.GETFAIL.getStatus().byteValue() == userStatus.getCreditCardAuthorize()) {
            responseDTO.setCreditCardAuthorize(Byte.valueOf("0"));
            responseDTO.setCreditCardTime(userStatus.getCreditCardTime());
        }
        if (userStatus.isCreditCardOverdue() || UserDataStatusEnum.CreditCardStatus.EXPIRED.getStatus().byteValue() == userStatus.getCreditCardAuthorize()) {
            responseDTO.setCreditCardAuthorize(Byte.valueOf("3"));
            responseDTO.setCreditCardTime(userStatus.getCreditCardTime());
        }

        // 学历状态转换
        if (!userStatus.isEducationOverdue() && UserDataStatusEnum.EducationStatus.GETFAIL.getStatus().byteValue() == userStatus.getEducationAuthorize()) {
            responseDTO.setEducationAuthorize(Byte.valueOf("0"));
            responseDTO.setEducationTime(userStatus.getEducationTime());
        }
        if (userStatus.isEducationOverdue() || UserDataStatusEnum.EducationStatus.EXPIRED.getStatus().byteValue() == userStatus.getEducationAuthorize()) {
            responseDTO.setEducationAuthorize(Byte.valueOf("3"));
            responseDTO.setEducationTime(userStatus.getEducationTime());
        }

        // 淘宝状态转换
        if (!userStatus.isTaobaoAuthOverdue() && UserDataStatusEnum.TaobaoStatus.GETFAIL.getStatus().byteValue() == userStatus.getTaobaoAuthorize()) {
            responseDTO.setTaobaoAuthorize(Byte.valueOf("0"));
            responseDTO.setTaobaoAuthTime(userStatus.getTaobaoAuthTime());
        }
        if (userStatus.isTaobaoAuthOverdue() || UserDataStatusEnum.TaobaoStatus.EXPIRED.getStatus().byteValue() == userStatus.getTaobaoAuthorize()) {
            responseDTO.setTaobaoAuthorize(Byte.valueOf("3"));
            responseDTO.setTaobaoAuthTime(userStatus.getTaobaoAuthTime());
        }
        
        // 京东状态转换
        if (!userStatus.isJdAuthOverdue() && UserDataStatusEnum.JdStatus.GETFAIL.getStatus().byteValue() == userStatus.getJdAuthorize()) {
            responseDTO.setJdAuthorize(Byte.valueOf("0"));
            responseDTO.setJdAuthTime(userStatus.getJdAuthTime());
        }
        if (userStatus.isJdAuthOverdue() || UserDataStatusEnum.JdStatus.EXPIRED.getStatus().byteValue() == userStatus.getJdAuthorize()) {
            responseDTO.setJdAuthorize(Byte.valueOf("3"));
            responseDTO.setJdAuthTime(userStatus.getJdAuthTime());
        }
        log.info("UserDataDubbServiceImpl.loanDataAuthentication responseDTO={}", JSON.toJSON(responseDTO));
        return responseDTO;
    }

    /**
     * 查询用户借款资料认证状态
     */
    private UserCreditDataStatusResponseDTO selectUserDataStatus(LoanDataAuthenticationRequestDTO requestDTO) {

        UserCreditDataStatusResponseDTO responseDTO = new UserCreditDataStatusResponseDTO();
        List<DataStatus> dataStatusList = Optional.ofNullable(ucDataStatusMapperExt.getDataStatusByUserId(requestDTO.getUserId())).orElse(Collections.emptyList());

        // 人个资料
        responseDTO.setPersonalInfo(UserDataStatusEnum.PersonInfoStatus.NOFILL.getStatus());
        dataStatusList.stream().filter(s -> Objects.equals(s.getDataType(), UserDataTypeEnum.PERSONAL_INFO.getValue())).findFirst()
                .ifPresent(dataStatus ->{
                    responseDTO.setPersonalInfo(dataStatus.getDataStatus());
                    if(UserDataStatusEnum.PersonInfoStatus.COMPLETE.getStatus().equals(dataStatus.getDataStatus())){
                        responseDTO.setPersonalInfo(this.getUserPersonalInfoStatus(requestDTO.getUserId()));
                    }
                });

        // 二要素
        responseDTO.setTwoElement(UserDataStatusEnum.RealNameAuthStatus.NOT_CERTIFIED.getStatus());
        dataStatusList.stream().filter(s -> Objects.equals(s.getDataType(), UserDataTypeEnum.TWO_ELEMENT.getValue())).findFirst()
                .ifPresent(dataStatus -> responseDTO.setTwoElement(dataStatus.getDataStatus()));

        // 肖像认证
        responseDTO.setPortraitAuthStatus(UserDataStatusEnum.PortraitAuthStatus.NOT_CERTIFIED.getStatus());
        dataStatusList.stream().filter(s -> Objects.equals(s.getDataType(), UserDataTypeEnum.PORTRAIT.getValue())).findFirst()
                .ifPresent(dataStatus -> responseDTO.setPortraitAuthStatus(dataStatus.getDataStatus()));
        // OCR
        responseDTO.setOcrStatus(UserDataStatusEnum.OCRStatus.NOT_OCR.getStatus());
        dataStatusList.stream().filter(s -> Objects.equals(s.getDataType(), UserDataTypeEnum.OCR.getValue())).findFirst()
                .ifPresent(dataStatus -> responseDTO.setOcrStatus(dataStatus.getDataStatus()));

        // 运营商
        responseDTO.setPhoneOperatorStatus(UserDataStatusEnum.PhoneOperatorStatus.NOCREDIT.getStatus());
        dataStatusList.stream().filter(s -> Objects.equals(s.getDataType(), UserDataTypeEnum.OPERATOR_AUTHORIZE.getValue())).findFirst()
                .ifPresent(dataStatus -> {
                    byte verificationState = UserDataStatusEnum.PhoneOperatorStatus.GETSUCCESS.getStatus();
                    byte updateState =  UserDataStatusEnum.PhoneOperatorStatus.EXPIRED.getStatus();
                    responseDTO.setPhoneOperatorOverdue(this.getUserAuthTime(verificationState, updateState, dataStatus, requestDTO.getMobileServicePeriod()));
                    responseDTO.setPhoneOperatorStatus(dataStatus.getDataStatus());
                });

        // 京东
        responseDTO.setJdAuthorize(UserDataStatusEnum.JdStatus.NOCREDIT.getStatus());
        dataStatusList.stream().filter(s -> Objects.equals(s.getDataType(), UserDataTypeEnum.JD_AUTHORIZE.getValue())).findFirst()
                .ifPresent(dataStatus -> {
                    byte verificationState = UserDataStatusEnum.JdStatus.GETSUCCESS.getStatus();
                    byte updateState =  UserDataStatusEnum.JdStatus.EXPIRED.getStatus();
                    responseDTO.setJdAuthOverdue(this.getUserAuthTime(verificationState, updateState, dataStatus, requestDTO.getJingdongAuthPeriod()));
                    responseDTO.setJdAuthorize(dataStatus.getDataStatus());
                    responseDTO.setJdAuthTime(dataStatus.getAuthTime());
                });
        
        // 淘宝认证
        responseDTO.setTaobaoAuthorize(UserDataStatusEnum.TaobaoStatus.NOCREDIT.getStatus());
        dataStatusList.stream().filter(s -> Objects.equals(s.getDataType(), UserDataTypeEnum.TAOBAO_AUTHORIZE.getValue())).findFirst()
                .ifPresent(dataStatus -> {
                	// 是否过期（过期并更新状态）
					Boolean isOverdue = getUserAuthTime(UserDataStatusEnum.TaobaoStatus.GETSUCCESS.getStatus(),
							UserDataStatusEnum.TaobaoStatus.EXPIRED.getStatus(), dataStatus,
							requestDTO.getTaobaoAuthPeriod());
                    responseDTO.setTaobaoAuthOverdue(isOverdue);
                    responseDTO.setTaobaoAuthorize(dataStatus.getDataStatus());
                    responseDTO.setTaobaoAuthTime(dataStatus.getAuthTime());
                });        

        // 学历
        responseDTO.setEducationAuthorize(UserDataStatusEnum.EducationStatus.NOCREDIT.getStatus());
        dataStatusList.stream().filter(s -> Objects.equals(s.getDataType(), UserDataTypeEnum.EDUCATION_AUTHORIZE.getValue())).findFirst()
                .ifPresent(dataStatus -> {
                    byte verificationState = UserDataStatusEnum.EducationStatus.GETSUCCESS.getStatus();
                    byte updateState =  UserDataStatusEnum.EducationStatus.EXPIRED.getStatus();
                    responseDTO.setEducationOverdue(this.getUserAuthTime(verificationState, updateState, dataStatus, requestDTO.getEducationQualificationPeriod()));
                    responseDTO.setEducationAuthorize(dataStatus.getDataStatus());
                    responseDTO.setEducationTime(dataStatus.getAuthTime());
                });

        // 信用卡
        responseDTO.setCreditCardAuthorize(UserDataStatusEnum.CreditCardStatus.NOCREDIT.getStatus());
        dataStatusList.stream().filter(s -> Objects.equals(s.getDataType(), UserDataTypeEnum.CREDIT_CARD_AUTHORIZE.getValue())).findFirst()
                .ifPresent(dataStatus -> {
                    byte verificationState = UserDataStatusEnum.CreditCardStatus.GETSUCCESS.getStatus();
                    byte updateState =  UserDataStatusEnum.CreditCardStatus.EXPIRED.getStatus();
                    responseDTO.setCreditCardOverdue(this.getUserAuthTime(verificationState, updateState, dataStatus, requestDTO.getCreditCardPeriod()));
                    responseDTO.setCreditCardAuthorize(dataStatus.getDataStatus());
                    responseDTO.setCreditCardTime(dataStatus.getAuthTime());
                });

        // 社保
        responseDTO.setSocialSecurityStatus(UserDataStatusEnum.SocialSecurityStatus.NOCREDIT.getStatus());
        dataStatusList.stream().filter(s -> Objects.equals(s.getDataType(), UserDataTypeEnum.SOCIAL_SECURITY_OPERATOR_AUTHORIZE.getValue())).findFirst()
                .ifPresent(dataStatus -> {
                    byte verificationState = UserDataStatusEnum.SocialSecurityStatus.GETSUCCESS.getStatus();
                    byte updateState =  UserDataStatusEnum.SocialSecurityStatus.EXPIRED.getStatus();
                    responseDTO.setSocialSecurityOverdue(this.getUserAuthTime(verificationState, updateState, dataStatus, requestDTO.getSocialSecurityPeriod()));
                    responseDTO.setSocialSecurityStatus(dataStatus.getDataStatus());
                    responseDTO.setSocialSecurityTime(dataStatus.getAuthTime());
                });

        // OCR关闭的时候，给出手持照上传状态
        responseDTO.setHandPhotoStatus(Byte.valueOf("0"));
        if (requestDTO.getOcrScanSwitch() != null && requestDTO.getOcrScanSwitch().equals(Byte.valueOf("0"))) {
            UserImageFile imageFile = imageFileService.getByType(requestDTO.getUserId(), UserImgTypeEnum.IDCARD_IMAGE, UserImgTypeEnum.IDCARD_HAND_IMAGE);
            responseDTO.setHandPhotoStatus((imageFile != null ? Byte.valueOf("1") : Byte.valueOf("0")));
        }

        // 已OCR且二要素通过才进行身份证有效期判断
        responseDTO.setIdCardExpiredStatus(responseDTO.getOcrStatus() != null
                ? this.getUserCardStatus(responseDTO, requestDTO.getIdCardExpiryDatePeriod(), requestDTO.getUserId()) : Byte.valueOf("0"));

        log.info("UserDataDubbServiceImpl.selectUserDataStatus responseDTO={}", JSON.toJSON(responseDTO));
        return responseDTO;
    }

    /**
     * 判断过期时间:true 已过期更新数据库状态, false 未过期
     *
     * @param verificationState 验证状态类型
     * @param dataStatus        对应数据库记录
     * @param operatorExpire    过期时间
     * @return true 过期 false 未过期
     */
    private boolean getUserAuthTime(byte verificationState, byte updateState, DataStatus dataStatus, Integer operatorExpire) {
        if (verificationState == dataStatus.getDataStatus()) {
            DateTime authTime = new DateTime(dataStatus.getAuthTime());
            if (dataStatus.getAuthTime() != null && operatorExpire != null && authTime.plusDays(operatorExpire).isBeforeNow()) {
                DataStatus data = new DataStatus();
                data.setUserId(dataStatus.getUserId());
                data.setDataType(dataStatus.getDataType());
                data.setDataStatus(updateState);
                data.setAuthTime(new Date());
                ucDataStatusMapperExt.updateByUserIdAndType(data);
                log.info("UserStatusService.getAuthTime DataStatus={}", JSON.toJSON(data));
                return true;
            }
        }
        return false;
    }

    /**
     * 身份证过期状态 0、未过期 1、快过期 2、已过期
     *
     * @param dataStatus 身份状态记录
     * @param userId     用户ID
     * @return 对应状态值
     */
    private Byte getUserCardStatus(UserCreditDataStatusResponseDTO dataStatus, Integer idCardExpiryDatePeriod, String userId) {
        if (dataStatus.getOcrStatus() == UserDataStatusEnum.OCRStatus.YES_OCR.getStatus().byteValue() &&
                dataStatus.getTwoElement() == UserDataStatusEnum.RealNameAuthStatus.PASS_CERTIFIED.getStatus().byteValue()) {
            IdentityInfo identityInfo = userIdentityService.getByUserId(userId);
            idCardExpiryDatePeriod = idCardExpiryDatePeriod == null ? 30 : idCardExpiryDatePeriod;
            if (identityInfo.getEndDate() != null) {
                DateTime idCardExpiredTime = new DateTime(identityInfo.getEndDate());
                if (idCardExpiredTime.isBeforeNow()) {
                    return UserDataStatusEnum.IdCardExpiredStatus.EXPIRED.getStatus();
                } else if (idCardExpiredTime.minusDays(idCardExpiryDatePeriod).isBeforeNow()) {
                    // 身份证有效期距离有效期截止日期30天以内,则为快过期
                    return UserDataStatusEnum.IdCardExpiredStatus.EXPIRING.getStatus();
                }
            }
        }
        return UserDataStatusEnum.IdCardExpiredStatus.VALID.getStatus();
    }

    /**
     * 查询确认用户资料是否完善
     */
    public Byte getUserPersonalInfoStatus(String userId) {
        UserPersonalInfo personalInfo = userPersonalInfoMapper.selectByPrimaryKey(userId);
        UserProfessionInfo professionInfo = userProfessionInfoMapper.selectByPrimaryKey(userId);
        List<UserLinkmanInfo> linkmanInfoList = userLinkmanInfoMapper.selectByUserId(userId);
        log.info("UserStatusService.getUserPersonalInfoStatus personalInfo={},professionInfo={},linkmanInfoList={}", JSON.toJSON(personalInfo), JSON.toJSON(professionInfo), JSON.toJSON(linkmanInfoList));
        Byte status = UserDataStatusEnum.PersonInfoStatus.NOFILL.getStatus();
        if (personalInfo == null || professionInfo == null || linkmanInfoList == null) {
            return this.updateUserDataStatus(userId, status);
        }

        // 判断个人信息与职业信息是否完善
        if (StringUtils.isAnyBlank(personalInfo.getUserId(), personalInfo.getEmail(), personalInfo.getLivingProvince(),
                personalInfo.getLivingCity(), personalInfo.getLivingArea(), personalInfo.getLivingAddress(),
                professionInfo.getUserId(), professionInfo.getCompanyName(), professionInfo.getCompanyProvince(),
                professionInfo.getCompanyCity(), professionInfo.getCompanyArea(), professionInfo.getCompanyAddress(),
                professionInfo.getCompanyPhone(), professionInfo.getDepartment())) {
            return this.updateUserDataStatus(userId, status);
        }

        // 判断联系人信息是否完善
        for (UserLinkmanInfo linkmanInfo : linkmanInfoList) {
            if (StringUtils.isAnyBlank(linkmanInfo.getUserId(), linkmanInfo.getName(), linkmanInfo.getMobileNo())) {
                return this.updateUserDataStatus(userId, status);
            }
        }

        return this.updateUserDataStatus(userId, UserDataStatusEnum.PersonInfoStatus.COMPLETE.getStatus());
    }

    private Byte updateUserDataStatus(String userId, Byte status) {
        DataStatus dataStatus = new DataStatus();
        dataStatus.setUserId(userId);
        dataStatus.setDataType(UserDataTypeEnum.PERSONAL_INFO.getValue());
        dataStatus.setDataStatus(status);
        dataStatus.setAuthTime(new Date());
        ucDataStatusMapperExt.updateByUserIdAndType(dataStatus);
        log.info("UserStatusService.getUserPersonalInfoStatus DataStatus={}", JSON.toJSON(dataStatus));
        return status;
    }


}
